import re

#读取srt字幕文件，转换为元组的数组，元组为字幕开始毫秒、结束毫秒、字幕数组
#例如： [(4234231233,423423433,["你好","hello"])]
def parser_srt(srt_file,encode):   
    subtitles = [] 
    with open(srt_file,"r",encoding=encode) as f:
        lines = f.read().splitlines()
        i = 0
        while i<len(lines):
            line = lines[i]
            match = re.match(r"(\d+):(\d+):(\d+),(\d+) --> (\d+):(\d+):(\d+),(\d+)", line)           
            if match:
                sHour, sMin,sSec, sMill,eHour, eMin,eSec, eMill, = map(int, match.groups()[:8])
                texts = []
                i = i + 1
                while i<len(lines) and len(lines[i]) > 0:
                    texts.append(lines[i]);
                    i = i + 1
                subtitles.append((sHour*60*60*1000+sMin*60*1000+sSec*1000+sMill,eHour*60*60*1000+eMin*60*1000+eSec*1000+eMill,texts))
            else:         
                i = i + 1     
    return subtitles

#把字幕按照最长宽度进行分行。texts为字幕数组。font为字体，maxWidth为最大长度，bySpace是否按空格分割
def truncat_srt(texts,font,maxWidth,bySpace):
    #返回处理后的字幕结果
    result = []
    for text in texts:
        if font.getlength(text) <= maxWidth:
            result.append(text)
        else:
            if bySpace:
                tmpstring = ""  
                for word in text.split(" "):
                    wordLen = font.getlength(word)
                    #如果当前单词超过最大长度，那么加入新的一行
                    if wordLen > maxWidth:
                        if len(tmpstring) > 0:
                            result.append(tmpstring)
                            tmpstring = "" 
                        result.append(word)
                    else :    
                        if font.getlength(tmpstring) + font.getlength(word) > maxWidth:
                            result.append(tmpstring)
                            tmpstring = word
                        else: 
                            tmpstring = tmpstring +" "+ word
                result.append(tmpstring)            
            else:
                tmpstring = ""      
                for char in text:
                    if font.getlength(tmpstring) + font.getlength(char) > maxWidth:
                        result.append(tmpstring)
                        tmpstring = char
                    else: 
                        tmpstring = tmpstring + char
                result.append(tmpstring)               
    return result       